const Topic = require("../db/model/topics")
const User = require("../db/model/users")
const Question = require("../db/model/questions")
const { SuccessModel, ErrorModel } = require("../utils/resModel")

class TopicCtl {
    /**
     * 获取话题列表
     * @param {*} ctx 
     */
    async find(ctx) {
        const { per_page = 10 } = ctx.query
        const perPage = Math.max(parseInt(per_page), 1) // 每次查询条数
        const page = Math.max(parseInt(ctx.query.page), 1) - 1   // 当前的页数
        // limit()指定查询的条数， skip()指定跳过多少条返回
        const list = await Topic.find({ name: new RegExp(ctx.query.q) }).limit(perPage).skip(page * perPage)
        ctx.body = new SuccessModel(list)
    }

    /**
     * 根据id查询一个话题
     * @param {*} ctx 
     */
    async findById(ctx) {
        const { fields = "" } = ctx.query
        let selectFields = fields.split(";").filter(f => f).map(f => ' +' + f).join(" ")
        const topic = await Topic.findById(ctx.params.id).select(selectFields)
        ctx.body = new SuccessModel(topic)
    }


    /**
     * 查询话题是否存在
     * @param {*} ctx 
     * @param {*} next 
     */
    async checkTopicExist(ctx, next) {
        try {
            const topic = await Topic.findById(ctx.params.id)
            if (!topic) {
                ctx.throw(404)
            }
        } catch (err) {
            ctx.throw(404, "话题ID错误")
        } finally {
            await next()
        }
    }

    /**
     * 创建一个话题
     * @param {*} ctx 
     */
    async create(ctx) {
        ctx.verifyParams({
            name: { type: "string", required: true },
            avatar_url: { type: "string", required: false },
            introduction: { type: "string", required: false }
        })
        const topic = await new Topic(ctx.request.body).save()
        ctx.body = new SuccessModel(topic)
    }

    /**
     * 修改一个话题
     * @param {*} ctx 
     */
    async update(ctx) {
        ctx.verifyParams({
            name: { type: "string", required: false },
            avatar_url: { type: "string", required: false },
            introduction: { type: "string", required: false }
        })
        const topic = await Topic.findByIdAndUpdate(ctx.params.id, ctx.request.body)
        ctx.body = new SuccessModel(topic)
    }

    /**
     * 获取话题关注者列表
     * @param {*} ctx 
     */
    async listTopicFollowers(ctx) {
        const users = await User.find({ followingTopics: ctx.params.id })
        ctx.body = new SuccessModel(users)
    }

    /**
     * 列出当前话题下的问题列表
     * @param {*} ctx 
     */
    async listQuestions(ctx) {
        const questions = await Question.find({ topics: ctx.params.id })
        ctx.body = new SuccessModel(questions)
    }
}



module.exports = new TopicCtl()